import { reqChangePwd, reqCheckPwd } from "@/api/reqUser"
import type { USER } from "@/types/user"
import { ElMessage, type FormInstance, type FormRules } from "element-plus"
import { reactive, ref, type Ref } from "vue"

export const useDialog = function (user: Ref<USER>, logOut: any) {
  const dialogVisable = ref(false)
  const formEle = ref<FormInstance>()
  //  表单数据
  const passForm = reactive({
    oldPass: "",
    newPass: "",
    checkPass: "",
  })

  const checkOldPass = (rules: any, value: string, callback: any) => {
    if (value === "") {
      callback(new Error("请输入原始密码"))
    } else {
      // 验证原始密码是否正确
      ;(async () => {
        const { msg, status } = await reqCheckPwd({
          userId: user.value._id as string,
          password: value,
        })
        if (status === 0) {
          callback()
        } else {
          callback(new Error(msg))
        }
      })()
    }
  }

  const checkPass = (rules: any, value: string, callback: any) => {
    if (value === "") {
      callback(new Error("请再次输入密码"))
    } else {
      if (value === passForm.newPass) {
        callback()
      } else {
        callback(new Error("两次密码不一致"))
      }
    }
  }

  //  表单的校验规则
  const rules = reactive<FormRules<typeof passForm>>({
    oldPass: [
      {
        validator: checkOldPass,
        trigger: "blur",
      },
    ],
    newPass: [
      { required: true, message: "请输入新密码", trigger: "blur" },
      {
        min: 5,
        max: 12,
        message: "密码长度为5-12位",
        trigger: "blur",
      },
      {
        pattern: /^[a-zA-Z0-9]+$/,
        message: "密码只能由数字和字母构成",
        trigger: "blur",
      },
    ],
    checkPass: [
      {
        validator: checkPass,
        trigger: "blur",
      },
    ],
  })

  // 确定修改密码
  const submitChange = () => {
    formEle.value?.validate(async (val) => {
      if (val) {
        // 确认修改
        console.log("确认修改")
        const { msg, status } = await reqChangePwd({
          userId: user.value._id as string,
          password: passForm.newPass,
        })
        if (status === 0) {
          // 修改成功
          ElMessage({
            type: "success",
            message: msg,
          })
          // 退出并重新登录
          logOut()
        }
      } else {
      }
    })
  }

  // 当dialog关闭时，处理相关逻辑
  const close = () => {
    // 表单清空
    formEle.value?.resetFields()
    // 关闭
    dialogVisable.value = false
  }

  return {
    dialogVisable,
    passForm,
    formEle,
    rules,
    submitChange,
    close,
  }
}

// // typeof 类型中的 返回实例的类型
// //   const user = {
// //     name: "小丁",
// //     age: 18,
// //   }

// //   type myType = typeof user
